package com.zyg.date;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DateTimeParseDemo {
    public static void main(String[] args) {
        final ExecutorService executorService = Executors.newFixedThreadPool(100);
        /**
         * 1.多线程下采用SimpleDateFormat，可能出现线程安全问题（SimpleDateFormat线程不安全）
         */
        // 1.1 format和parse均用SimpleDateFormat
        //结论：会出现线程安全问题
        Date now = new Date();
        for (int i = 0; i < 1000; i++) {
            executorService.execute(()-> {
                //System.out.println("当前执行的线程为------》"+Thread.currentThread().getName());
                System.out.println("解析后的时间为--------》"+formatAndParseDateBySimpleDate(now));
            });
        }
        //1.2 format用SimpleDateFormat,parse用Datetimeformatter
        //结论：不会出现线程安全问题
        for (int i = 0; i < 1000; i++) {
            executorService.execute(()-> {
                //System.out.println("当前执行的线程为------》"+Thread.currentThread().getName());
                System.out.println("解析后的时间为--------》"+formatBySimpleAndParseByDateTimeFormatter(now));
            });
        }
        //2：多线程下采用DateTimeFormatter，不会出现线程安全问题
        LocalDateTime nowDateTime = LocalDateTime.now();
        for (int i = 0; i < 1000; i++) {
            executorService.execute(()-> {
                //System.out.println("当前执行的线程为------》"+Thread.currentThread().getName());
                System.out.println("解析后的时间为--------》"+formatAndParseDateTime(nowDateTime));
            });
        }
        executorService.shutdown();
        System.out.println("main end");

    }

    private static Date formatAndParseDateBySimpleDate(Date now) {
        String format = SimpleDateFormatUtil.format(now);
        return SimpleDateFormatUtil.parse(format);
    }

    private static LocalDateTime formatBySimpleAndParseByDateTimeFormatter(Date now) {
        String format = SimpleDateFormatUtil.format(now);
        return DateTimeFormatterUtil.parse(format);
    }

    private static LocalDateTime formatAndParseDateTime(LocalDateTime now) {
        String format = DateTimeFormatterUtil.format(now);
        return DateTimeFormatterUtil.parse(format);
    }

}


